<?php
/**
 * Costs Controller
 * 
 * @author CRIA Groep 1 <project@markvink.nl>
 * @version 1.0
 * @package controllers
 */
class CostsController extends AppController {
	/**
    * @var string Controller name (faster in PHP 4)
    */
	var $name = 'Costs';
	/**
    * @var string Scaffolding on prefix 
    */	
	var $scaffold = 'admin';
	
	/**
    * @var array uses following Models
    */
	var $uses = array('Cost', 'Usagetype');
	
	/**
	 * Function admin_index
	 * 
	 * Controller action, only accessible by admin prefix
	 */
	function admin_index() {
		$countries = $this->Cost->Country->find('list');
		$this->set(compact('countries'));
		if($this->data) {
			$this->redirect(array('controller' => 'costs', 'action' => 'edit', $this->data['Cost']['country_id']));
		}
	}
	
	/**
	 * Private function __setData
	 * 
	 * Set data to view.
	 * @param integer $id identifier
	 */
	function __setData($id) {
		$country = $this->Cost->Country->field('Country.name', array('Country.id' => $id));
		$data = $this->Cost->findAllByCountryId($id);
		$additivetypes = $this->Usagetype->find('all', array(
			'conditions' => array('Usagetype.type' => 'additive')    
		));
		$energytypes = $this->Usagetype->find('all', array(
			'conditions' => array('Usagetype.type' => 'energy')    
		));
		
		$this->set(compact('data', 'country', 'additivetypes', 'energytypes'));
	}
	
	/**
	 * Function admin_edit
	 * 
	 * Controller action, only accessible by admin prefix
	 * @param integer $id identifier
	 */
	function admin_edit($id = null) {
		$this->__setData($id);
		
		if($this->data) {
			foreach($this->data['Cost'] AS $usagetype => $array) {
				if(isset($array) && is_array($array)) {
					$this->Cost->update($usagetype, $id, $array['cost'], $array['emission']);
				}
			}
			$this->redirect(array('prefix' => 'admin', 'controller' => 'costs', 'action' => 'edit', $id));
		}
	}
}
